package com.litidea.actions;

import static com.litidea.commons.dict.StaticDics.ROLE_TYPE_CODE_LIST;
import static com.litidea.commons.keys.SystemKeys.ADD_DEPT_CHILD_TYPE;
import static com.litidea.commons.keys.SystemKeys.ADD_DEPT_SIBILING_TYPE;
import static com.litidea.commons.keys.SystemKeys.DEFAULT_JSONARRAY_STR;
import static com.litidea.commons.keys.SystemKeys.DEL_DEPT;
import static com.litidea.commons.keys.SystemKeys.EDIT_DEPT;
import static com.litidea.commons.keys.SystemKeys.MOVE_DEPT;
import static com.litidea.commons.keys.SystemKeys.PUB_ADD_OPTION;
import static com.litidea.commons.keys.SystemKeys.PUB_DEL_OPTION;
import static com.litidea.commons.keys.SystemKeys.PUB_EDIT_OPTION;
import static com.litidea.commons.keys.SystemKeys.PUB_SELECTED;
import static com.litidea.commons.keys.SystemKeys.PUB_WAIT_SELECT;
import static com.litidea.commons.keys.SystemKeys.SET_DEPT_MGR;
import static com.litidea.commons.paramkeys.SystemParamKeys.SAVE_DEPT_PARAMS;
import static com.litidea.commons.paramkeys.SystemParamKeys.SAVE_ROLE_PARAMS;
import static com.litidea.commons.paramkeys.SystemParamKeys.SAVE_USER_DATES;
import static com.litidea.commons.paramkeys.SystemParamKeys.SAVE_USER_PARAMS;
import static com.litidea.commons.paramkeys.SystemParamKeys.SEARCH_ROLE_PARAMS;
import static com.litidea.commons.paramkeys.SystemParamKeys.SEARCH_USER_DATES;
import static com.litidea.commons.paramkeys.SystemParamKeys.SEARCH_USER_PARAMS;
import static com.litidea.commons.tools.ConvertPassword.getMyPassword;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.litidea.commons.dict.StaticDics;
import com.litidea.commons.utils.MenuUtils;
import com.litidea.dao.SystemDAO;
import com.litidea.dataobjects.DepartmentDO;
import com.litidea.dataobjects.KValueDO;
import com.litidea.dataobjects.MenuNodeDO;
import com.litidea.dataobjects.RoleDO;
import com.litidea.dataobjects.UserDO;
import com.litidea.dataobjects.UserLoginDO;
import com.litidea.filters.FilterProcessor;
import com.opensymphony.xwork2.Action;

public class SystemManageAction extends BaseAction implements Action {

	/**
	 * 序列码
	 */
	private static final long serialVersionUID = 968674751758541095L;

	private SystemDAO systemDAO;

	public void setSystemDAO(SystemDAO systemDAO) {
		this.systemDAO = systemDAO;
	}

	/**
	 * 获取部门列表
	 * 
	 * @return
	 */
	public String getDepartments() {
		List<DepartmentDO> list = systemDAO.getAllDepartMents();
		return responseAjax(MenuUtils.convertMenus(list, 1));
	}

	/**
	 * 获取需要用来选择的组织列表
	 * 
	 * @return
	 */
	public String getCheckDeparentMents() {
		List<DepartmentDO> list = systemDAO.getAllDepartmentByParent();
		List<KValueDO> result = new ArrayList<KValueDO>(list.size());
		for (DepartmentDO dept : list) {
			result.add(new KValueDO(dept.getId().toString(), dept
					.getDeptFullName()));
		}
		return responseAjax(result);
	}

	/**
	 * 保存部门信息
	 * 
	 * @return
	 */
	public String saveDepartment() {
		String success = null, errorInfo = null;
		try {
			Map<String, String> params = getParameters(SAVE_DEPT_PARAMS);
			int type = Integer.valueOf(params.get("type"));
			switch (type) {
			case ADD_DEPT_CHILD_TYPE:
				success = systemDAO.saveChildDepartment(params);
				break;
			case ADD_DEPT_SIBILING_TYPE:
				success = systemDAO.addSiblingDepartment(params);
				break;
			case EDIT_DEPT:
				success = systemDAO.editDepartMent(params);
				break;
			case DEL_DEPT:
				success = systemDAO.delDeparentMent(params);
				break;
			case MOVE_DEPT:
				success = systemDAO.moveDepartMent(params);
				break;
			case SET_DEPT_MGR:
				success = systemDAO.setDeptMgr(params);
				break;
			}
			success = "保存部门成功";
		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 获取部门的类型列表
	 * 
	 * @return
	 */
	public String getDeptTypes() {
		List<KValueDO> deptTypeList = StaticDics.DEPT_TYPE_CODE_LIST;
		return responseAjax(deptTypeList);
	}

	/**
	 * 是否包含子部门
	 * 
	 * @return
	 */
	public String hasChildDepartment() {
		String id = getString("id");
		boolean hasChild = systemDAO.getHasChildNum(id);
		return responseAjax(hasChild ? "1" : "0");
	}

	/**
	 * 将部门列表转换为K-V结构格式
	 * 
	 * @return
	 */
	public String getDepartmentKV() {
		List<DepartmentDO> list = systemDAO.getAllDepartmentByParent();
		List<KValueDO> realList = convertDeptToKV(list);
		return responseAjax(realList);
	}

	/**
	 * 将部门信息转换为KV结构
	 * 
	 * @param list
	 * @return
	 */
	private List<KValueDO> convertDeptToKV(List<DepartmentDO> list) {
		List<KValueDO> realList = new ArrayList<KValueDO>(list.size());
		for (DepartmentDO deptDO : list) {
			realList.add(new KValueDO(deptDO.getDeptId().toString(), deptDO
					.getDeptFullName()));
		}
		return realList;
	}

	/**
	 * 返回role列表信息
	 * 
	 * @return
	 */
	public String getRoles() {
		Map<String, String> params = getParameters(SEARCH_ROLE_PARAMS);
		return responseAjax(systemDAO.getRolePageList(params).toString());
	}

	/**
	 * 用户角色类型获取
	 * 
	 * @return
	 */
	public String getRoleTypes() {
		return responseAjax(ROLE_TYPE_CODE_LIST);
	}

	/**
	 * 保存角色信息
	 * 
	 * @return
	 */
	public String saveRole() {
		Map<String, String> params = getParameters(SAVE_ROLE_PARAMS);
		String success = "角色信息操作成功。", errorInfo = null;
		try {
			int type = Integer.valueOf(params.get("type"));
			switch (type) {
			case PUB_ADD_OPTION:
				systemDAO.addNewRole(params);
				break;
			case PUB_EDIT_OPTION:
				systemDAO.editRole(params);
				break;
			case PUB_DEL_OPTION:
				systemDAO.delRole(params);
				break;
			}
		} catch (Exception e) {
			errorInfo = e.toString();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 获取所有菜单，并根据role填充是否选中
	 * 
	 * @return
	 */
	public String getAllRoleMenus() {
		List<MenuNodeDO> allMenus = systemDAO.getAllMenus();
		String roleId = getString("roleId");
		Map<String, Integer> userMenus = systemDAO.getRoleMenus(roleId);
		return responseAjax(MenuUtils.convertMenus(allMenus, 1, userMenus));
	}

	/**
	 * 保存角色的菜单信息
	 * 
	 * @return
	 */
	public String saveRoleMenus() {
		String[] menus = this.getStrings("ids");
		String roleId = this.getString("roleId");
		String success = "角色对应菜单授权操作成功。", errorInfo = null;
		try {
			systemDAO.saveRoleMenus(menus, roleId);
		} catch (Exception e) {
			errorInfo = e.toString();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 获取用户列表
	 * 
	 * @return
	 */
	public String getUsers() {
		Map<String, String> params = getParameters(SEARCH_USER_PARAMS,
				SEARCH_USER_DATES);
		return responseAjax(systemDAO.getUserPageList(params).toString());
	}
	
	/**
	 * 获取用户列表
	 * 
	 * @return
	 */
	public String getUsersByDept() {
		Integer deptId = this.getInt("deptId");
		List<UserDO> list = systemDAO.getUserByDept(deptId);
		List<KValueDO> result = new ArrayList<KValueDO>(list.size());
		for (UserDO user : list) {
			result.add(new KValueDO(user.getId().toString(), user
					.getName()));
		}
		return responseAjax(result);
	}

	/**
	 * 保存用户信息
	 */
	public String saveUser() {
		Map<String, String> params = getParameters(SAVE_USER_PARAMS,
				SAVE_USER_DATES);
		String success = "用户信息操作成功。", errorInfo = null;
		try {
			int type = Integer.valueOf(params.get("type"));
			switch (type) {
			case PUB_ADD_OPTION:
				systemDAO.addNewUser(params);
				break;
			case PUB_EDIT_OPTION:
				systemDAO.editUser(params);
				break;
			case PUB_DEL_OPTION:
				systemDAO.delUser(params);
				break;
			}
		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 根据用户信息获取User
	 * 
	 * @return
	 */
	public String getRoleByUser() {
		int type = getInt("type");
		List<RoleDO> list = null;
		try {
			switch (type) {
			case PUB_WAIT_SELECT:
				list = systemDAO.getNotUserRoles(getString("id"),
						getString("name"));
				break;
			case PUB_SELECTED:
				list = systemDAO.getUserRoles(getString("id"));
				break;
			}
			;
			if (list == null) {
				return responseAjax(DEFAULT_JSONARRAY_STR);
			}
			return responseAjax(list);
		} catch (Exception e) {
			return responseAjax(DEFAULT_JSONARRAY_STR);
		}
	}

	/**
	 * 保存用户的角色信息
	 * 
	 * @return
	 */
	public String saveUserRoles() {
		String success = "用户角色授予操作成功。", errorInfo = null;
		try {
			systemDAO.saveUserRoles(getString("id"), getStrings("roles"));
		} catch (Exception e) {
			errorInfo = e.toString();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 重新设置个人密码
	 * 
	 * @return
	 */
	public String resetMyPassword() {
		String oldPass = getString("oldPass");
		String newPass = getString("newPass");
		String newPassConfirm = getString("newPassConfirm");
		UserLoginDO userLoginDO = this.findUserInfo();
		UserDO userDO = systemDAO
				.getUserByLoginName(userLoginDO.getLoginName());
		if (!FilterProcessor.checkPassword(oldPass, userDO)) {
			return this.normalResponse("旧密码测试未通过，不能修改。", null);
		}
		if (!newPass.equals(newPassConfirm)) {
			return this.normalResponse("新密码与确认密码不一致，不能修改。", null);
		}
		String errrorMsg = null;
		try {
			userDO.setUserPass(getMyPassword(newPass));
			systemDAO.chgUserPassWord(userDO);
		} catch (Exception e) {
			errrorMsg = e.getMessage();
		}
		return this.normalResponse(errrorMsg, "您的密码已经修改成功！");
	}

	/**
	 * 管理员设置密码
	 * 
	 * @return
	 */
	public String resetPasswordByAdmin() {
		String userId = getString("id");
		String password = getString("password");
		UserDO userDO = systemDAO.getUserByUserId(userId);
		if (userDO == null) {
			return this.normalResponse("找不到该用户", null);
		}
		String errrorMsg = null;
		try {
			userDO.setUserPass(getMyPassword(password));
			systemDAO.chgUserPassWord(userDO);
		} catch (Exception e) {
			errrorMsg = e.getMessage();
		}
		return this.normalResponse(errrorMsg, "密码已经修改成功，请告知相应的用户最新的密码！");
	}
}
